package gt

import (
	"gitee.com/dark.H/gs"
	termbox "github.com/nsf/termbox-go"
)

type App struct {
	Mode      string
	Size      int
	Fragments gs.Dict[AppPanel]
}

func NewApp() *App {
	return &App{
		Mode:      "",
		Size:      30,
		Fragments: make(gs.Dict[AppPanel]),
	}
}

func (app *App) Regist(mode string, fragment AppPanel) {
	if mode != "" {
		app.Fragments[mode] = fragment
	}

}

func (app *App) Start() {
	menuPanel := NewListPanel("Main Menu", app.Fragments.Keys(), app.Size)
	app.Regist("", menuPanel)
	Renderbar(func(row, width int) {
		OnSignal(func() {
			if f, ok := app.Fragments[app.Mode]; ok {
				f.Draw()
			}
		}, func(k termbox.Event) bool {
			if f, ok := app.Fragments[app.Mode]; ok {
				return f.OnKey(k)
			}
			return true
		})

	})
	return
}

func Select[T any](list gs.List[T]) (selected T) {
	ClearScreen()
	penels := NewListPanel[T]("Select item", list, 20)
	Renderbar(func(row, width int) {

		OnSignal(func() {
			penels.Draw()
		}, func(k termbox.Event) (ifbreak bool) {
			return penels.OnKey(k)
		})
	})

	// fmt.Println("oter:", penels.Selected)
	// time.Sleep(2 * time.Second)
	gs.Str("").ANSIRestore().Print()
	return penels.Selected
}
